<?php
/*
	Muffinz CMS - A website content management system.
	Copyright (C) 2010-2011 Sigitas Zelenkovas

	This program is free software; you can redistribute it and/or
	modify it under the terms of the GNU General Public License
	as published by the Free Software Foundation; either version 2
	of the License, or (at your option) any later version.

	This program is distributed in the hope that it will be useful,
	but WITHOUT ANY WARRANTY; without even the implied warranty of
	MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
	GNU General Public License for more details.

	You should have received a copy of the GNU General Public License
	along with this program; if not, write to the Free Software
	Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
	
	Optionally you can also view the license at <http://www.gnu.org/licenses/>.
*/

class DesignCore{
	private $template = null;
	private $tmplFile = "";
	private $theme = "";
	public $tmplFolder = "themes/";
	private $e = "";
	private $menuItems = array();
	private $menuItems_sec = array();
	private $panels = array();
	private $data = array();
	private $modules = array();
	private $panelMenuItems = array();
	private $specDir = "";
	private $specN = "";
	private $headerC = array();
	private $pgTitle = "";
	private $mErrors = array();
	private $mNotifications = array();
	private $cModulel = "";
	private $cModulesLoaded = array();
	private $params = array("content" => array("{{CONTENT}}", array("", ""), "rep"),
							//"head" => array("{{HEAD}}", array("", ""), "rep"),
							"footer" => array("{{FOOTER}}", array("", ""), "rep"),
							"subfooter" => array("{{SUBFOOTER}}", array("", ""), "rep"));
	
	public function __construct($dir = "", $sp =""){
		if(array_key_exists($sp."theme", $_SESSION)){
			if($_SESSION[$sp."theme"]["style"] != null){ $this->template = $_SESSION[$sp."theme"]["style"]; }
			if($_SESSION[$sp."theme"]["tmplFile"] != null){ $this->tmplFile = $_SESSION[$sp."theme"]["tmplFile"]; }
			if($_SESSION[$sp."theme"]["theme"] != null){ $this->theme = $_SESSION[$sp."theme"]["theme"]; }
		}
		if($dir != ""){ $this->specDir = $dir; }
		if($sp != ""){ $this->specN = $sp; }
		return true;
	}
	
	public function Theme($name = false){
		if($name == false){
			return $this->theme;
		}else {
			if(!array_key_exists($this->specN."theme", $_SESSION) && ($_SESSION[$this->specN."theme"]["tmplFile"] == null || $_SESSION[$this->specN."theme"]["theme"] == null || $_SESSION[$this->specN."theme"]["style"] == null)){
				if(file_exists($this->specDir.$this->tmplFolder."$name/template.php")){
					$this->tmplFile = "$name/template.php";
					$this->theme = $name;
					$this->template = fread(fopen($this->specDir.$this->tmplFolder.$this->tmplFile, 'r'), filesize($this->tmplFolder.$this->tmplFile));

					$_SESSION[$this->specN."theme"]["tmplFile"] = $this->tmplFile;
					$_SESSION[$this->specN."theme"]["theme"] = $this->theme;
					$_SESSION[$this->specN."theme"]["style"] = $this->template;
					return true;
				}else {
					$this->e = "Template file does not exist in specified template directory. (".$this->specDir.$this->tmplFolder."$name/template.php".")";
					return false;
				}
			}else {
				return true;
			}
		}
	}
	
	public function TitleBase($title){
		$this->template = str_replace("{{PAGETITLE}}", "<title>".$title.$this->pgTitle."</title>", $this->template);
		return true;
	}
	
	public function SetTitle($title){
		$this->pgTitle = $title;
		return true;
	}
	
	public function SetParam($param, $value){
		if($this->params[$param] == null){
			$this->e = "Parameter <b>$param</b> was not found in the configuration.";
			return false;
		}else {
			if($this->params[$param][2] == "rep"){
				$this->template = str_replace($this->params[$param][0], implode($value, $this->params[$param][1]), $this->template);
			}
			return true;
		}
	}
	
	public function AddModuleError($message){
		$this->mErrors[] = $message;
		return true;
	}
	
	private function parseModuleErrors(){
		$buffer = "";
		if(count($this->mErrors) != 0){			
			preg_match("/\{\{MODULEERROR\}\}(.*)\{\{\/MODULEERROR\}\}/", $this->template, $matches);
			$peaces = preg_split("/({{\w+}})/", $matches[1], -1, PREG_SPLIT_DELIM_CAPTURE);
			
			foreach($this->mErrors as $item){
				foreach($peaces as $pc){
					if($pc == "{{MODULEERRORTEXT}}"){ $pc = $item; }
					$buffer .= $pc;
				}
			}
		}
		$this->template = preg_replace("/\{\{MODULEERROR\}\}(.*)\{\{\/MODULEERROR\}\}/", $buffer, $this->template);
		return true;
	}
	
	public function AddModuleNotification($message){
		$this->mNotifications[] = $message;
		return true;
	}
	
	private function parseModuleNotifications(){
		$buffer = "";
		if(count($this->mNotifications) != 0){			
			preg_match("/\{\{MODULENOTIFICATION\}\}(.*)\{\{\/MODULENOTIFICATION\}\}/", $this->template, $matches);
			$peaces = preg_split("/({{\w+}})/", $matches[1], -1, PREG_SPLIT_DELIM_CAPTURE);
			
			foreach($this->mNotifications as $item){
				foreach($peaces as $pc){
					if($pc == "{{MODULENOTIFICATIONTEXT}}"){ $pc = $item; }
					$buffer .= $pc;
				}
			}
		}
		$this->template = preg_replace("/\{\{MODULENOTIFICATION\}\}(.*)\{\{\/MODULENOTIFICATION\}\}/", $buffer, $this->template);
		return true;
	}
	
	public function AddHeader($content){
		$this->headerC[] = $content;
		return true;
	}
	
	public function AddMenuItem($title = false, $link = false){
		if(!$title){
			$this->e = "Missing title parameter in <b>SetMenuItem(title, link)</b>";
			return false;
		}
		if(!$link){
			$this->e = "Missing link parameter in <b>SetMenuItem(title, link)</b>";
			return false;
		}
		
		if (!is_array($this->menuItems)) {
			throw new Exception('Menu items is not array!');
		}

		
		array_push($this->menuItems, array($title, $link));
		return true;
	}
	
	public function SetMenu(){		
		preg_match("/\{\{MENU\}\}(.*)\{\{\/MENU\}\}/", $this->template, $matches);
		$peaces = preg_split("/({{\w+}})/", $matches[1], -1, PREG_SPLIT_DELIM_CAPTURE);
		preg_match("/\{\{MSEP=(.*)\}\}/", $this->template, $seperator);
		
		$buffer = "";
		foreach($this->menuItems as $item){
			foreach($peaces as $pc){
				if($pc == "{{TITLE}}"){ $pc = $item[0]; }
				if($pc == "{{LINK}}"){ $pc = $item[1]; }
				$buffer .= $pc;
			}
			if(array_search($item, $this->menuItems) < count($this->menuItems) - 1) $buffer .= $seperator[1];
		}
		
		$this->template = preg_replace("/\{\{MENU\}\}(.*)\{\{\/MENU\}\}/", $buffer, $this->template);
		$this->template = preg_replace("/\{\{MSEP=(.*)\}\}/", "", $this->template);
		return true;
	}
	
	public function cModule($templateNamme, $dataArray, $inPanel = true){
		if($_SESSION[$this->specN."theme"]["cModule"][$templateNamme] == null){
			$_SESSION[$this->specN."theme"]["cModule"][$templateNamme] = fread(fopen($this->specDir.$this->tmplFolder.$this->theme."/custom/".$templateNamme.".tmpl.php", 'r'), filesize($this->tmplFolder.$this->theme."/custom/".$templateNamme.".tmpl.php"));
		}
		$buffer = $_SESSION[$this->specN."theme"]["cModule"][$templateNamme];
		
		foreach($dataArray as $name => $item){
			if(is_array($item)){
				$dbuffer = "";
				preg_match("/\{\{$name\}\}(.*)\{\{\/$name\}\}/", $buffer, $matches);
				$peaces = preg_split("/({{\w+}})/", $matches[1], -1, PREG_SPLIT_DELIM_CAPTURE);
				
				foreach($item as $va){
					foreach($peaces as $pc){
						foreach($va as $n => $v){
							if("{{{$n}}}" == $pc){
								$pc = $v;
							}
						}
						$dbuffer .= $pc;
					}
				}
				
				$buffer = preg_replace("/\{\{$name\}\}(.*)\{\{\/$name\}\}/", $dbuffer, $buffer);
			}else {
				if(strstr($buffer, "{{$name}}")){
					$buffer = str_replace("{{{$name}}}", $item, $buffer);
				}
			}
		}
		
		if($inPanel){
			return $buffer;
		}else {
			$this->cModulel .= $buffer;
		}
	}
	
	public function AddPanel($title, $content, $order){
		$this->panels[] = array($title, $content, $order);
		return true;
	}
	
	public function SetPanels(){
		if(count($this->panels) != 0){
			$this->panels = subval_sort($this->panels, 2);
			
			preg_match("/\{\{PANEL\}\}(.*)\{\{\/PANEL\}\}/", $this->template, $matches);
			$peaces = preg_split("/({{\w+}})/", $matches[1], -1, PREG_SPLIT_DELIM_CAPTURE);
			
			$buffer = "";
			foreach($this->panels as $item){
				foreach($peaces as $pc){
					if($pc == "{{PANELTITLE}}"){ $pc = $item[0]; }
					if($pc == "{{PANELCONTENT}}"){ $pc = $item[1]; }
					$buffer .= $pc;
				}
			}
		}
		$this->template = preg_replace("/\{\{PANEL\}\}(.*)\{\{\/PANEL\}\}/", $buffer, $this->template);
		return true;
	}
	
	public function AddModule($title, $content, $order, $footer = false){
		$this->modules[] = array($title, $content, $footer, $order);
		return true;
	}
	
	public function SetModules(){
		$buffer = "";
		if(count($this->modules) != 0){
			$this->modules = subval_sort($this->modules, 3);
			
			preg_match("/\{\{MFOOT\}\}(.*)\{\{\/MFOOT\}\}/", $this->template, $footer);
			$this->template = preg_replace("/\{\{MFOOT\}\}(.*)\{\{\/MFOOT\}\}/", "{{FOOT}}", $this->template);
			preg_match("/\{\{MODULE\}\}(.*)\{\{\/MODULE\}\}/", $this->template, $matches);
			
			$peaces = preg_split("/({{\w+}})/", $matches[1], -1, PREG_SPLIT_DELIM_CAPTURE);
			$fpeaces = preg_split("/({{\w+}})/", $footer[1], -1, PREG_SPLIT_DELIM_CAPTURE);
			
			foreach($this->modules as $item){
				foreach($peaces as $pc){
					if($pc == "{{MODULETITLE}}"){ $pc = $item[0]; }
					if($pc == "{{MODULECONTENT}}"){ $pc = $item[1]; }
					if($pc == "{{FOOT}}" && $item[2] != false){
						$pc = "";
						foreach($fpeaces as $fitem){
							if($fitem == "{{MODULEFOOTER}}"){ $fitem = $item[2]; }
							$pc .= $fitem;
						}
					}else if($pc == "{{FOOT}}" && $item[2] == false){ $pc = ""; }
					$buffer .= $pc;
				}
			}
		}
		$this->template = preg_replace("/\{\{MODULE\}\}(.*)\{\{\/MODULE\}\}/", $buffer, $this->template);
		return true;
	}
	
	public function ParseTemplate(){ 
		$this->parseModuleErrors();
		$this->parseModuleNotifications();
		
		preg_match_all("(\{\{VAR\:(web)\-(core_link_full|core_link|core_link_js|core_theme_footer)\}\})", $this->template, $matches, PREG_SET_ORDER);
		foreach($matches as $mach){
			$this->template = str_replace($mach[0], $_SESSION['sys'][$mach[2]], $this->template);
		}
		
		preg_match_all("(\{\{(CSS|THEME|CUSTOMMODULE)\}\})", $this->template, $stuff, PREG_SET_ORDER);
		foreach($stuff as $st){
			if($st[0] == "{{THEME}}"){ $this->template = str_replace("{{THEME}}", $this->specDir.$this->tmplFolder.$this->theme."/", $this->template); }
			if($st[0] == "{{CSS}}"){ $this->template = str_replace("{{CSS}}", $this->specDir.$this->tmplFolder.$this->theme."/style.css", $this->template); }
			if($st[0] == "{{CUSTOMMODULE}}"){ $this->template = str_replace("{{CUSTOMMODULE}}", $this->cModulel, $this->template); }
		}
		
		$buff = "";
		foreach($this->headerC as $hItem){
			$buff .= "$hItem";
		}
		$this->template = str_replace("{{HEAD}}", $buff, $this->template);
		
		echo $this->template;
		return true;
	}
	
	public function Error($line = false){
		if($line){ $str = "(<b>At line: $line</b>)"; }else { $str = ""; }
		return "<div style=\"font-size:12px;color:#000000;background-color:#ffd3d3;font-family:arial;padding:3px 5px;border:1px solid #b90000;\">". $this->e ." $str</div>";
	}
}